import { defineStore } from 'pinia'
import { getMenusByUserId, getUserInfo, login4User } from '@/service/login/user'
import { ElMessage } from 'element-plus'
import type { IAccount, IDecodeUserInfo, ILoginState } from '@/types'
import { localCache } from '@/utils/cache'
import { TOKEN_KEY } from '@/global/constant'
import { jwtDecode } from 'jwt-decode'

const login = defineStore('login', {
  state: (): ILoginState => ({
    token: localCache.getCache(TOKEN_KEY),
    userInfo: localCache.getCache('userInfo') ?? {},
    userMenus: localCache.getCache('userMenus') ?? []
  }),
  getters: {},
  actions: {
    async accountLoginAction(account: IAccount) {
      const { token, msg } = await login4User(account)
      if (!token) {
        return ElMessage.error({ message: msg })
      }

      this.token = token
      localCache.setCache(TOKEN_KEY, this.token)

      const decode: IDecodeUserInfo = jwtDecode(token)
      // 用户信息
      const { data: userInfo } = await getUserInfo(decode.id)
      this.userInfo = userInfo
      localCache.setCache('userInfo', userInfo)
      // 菜单
      const { data: userMenus } = await getMenusByUserId(decode.id)
      this.userMenus = userMenus
      localCache.setCache('userMenus', userMenus)
      ElMessage.success({ message: msg })
    },
    getCodeAction() {
      // remote
      return Promise.resolve('114541')
    }
  }
})

export default login
